JSONDealer = function (str) {
  this.data = null;
  this.path = new Array();
  //default baseURL + 'json'
  this.jsonPath = '';
  this.decode(str);
};

JSONDealer.prototype.decode = function(str) {
  this.data = JSON.parse(str);
  return this.data;
};

JSONDealer.prototype.encode = function() {
  return JSON.stringify(this.data);
};

JSONDealer.prototype.toString = function() {
  return this.encode();
};

JSONDealer.prototype.getCurrent = function() {
  return this.path.slice();
};

JSONDealer.prototype.resetCurrent = function(path) {
  if (path == undefined) {
    this.path = new Array();
  } else {
    //array pass as reference
    this.path = path.slice();
  }
};

JSONDealer.prototype.getPath = function() {
  var path = '';
  for (var item in this.path) {
    path += '[\'' + this.path[item] + '\']';
  }
  return path;
};

JSONDealer.prototype.getNode = function(id) {
  var path = '';
  if (id == undefined) {
    this.resetCurrent();
    path = this.getPath();
  } else {
    if (this.locateById(id)) {
      path = this.getPath();
      //restore the original node
      this.path.pop();
    } else {
      //not found
      return undefined;
    }
  }
  (eval ('(node= this.data' + path+')'));
  return node;
};

JSONDealer.prototype.createNode = function(name, val) {
  path = this.getPath();
  path = path + '[\'' + name + '\']';
  eval('(this.data' + path + '=\'\')');
  if (val) {
    this.locateById(name);
    this.setNode(val);
  }
  return true;
};

JSONDealer.prototype.setNode = function(val) {
  if (typeof val == 'object') {
    val = val.getNode();
  }
  path = this.getPath();
  eval('(this.data' + path + '=val)');
  return true;
};

JSONDealer.prototype.setNodeVal = function(node, val) {
  var current = this.getCurrent();
  this.locateById(node);
  this.setNode(val);
  this.resetCurrent(current);
  return true;
};

JSONDealer.prototype.removeNode = function(index) {
  node = this.getCurrentNode();
  if (typeof node == 'object') {
    var path = this.getPath();
    eval ('this.data' + path+'.splice(index, 1)');
  } else {
    //unset(node[index]);
  }
  return true;
};


JSONDealer.prototype.getType = function() {
  node = this.getCurrentNode();
  return node['type'];
};

JSONDealer.prototype.getCurrentNode = function() {
  path = this.getPath();
  var node = null;
  (eval ('(node= this.data' + path+')'));
  return node;
};

JSONDealer.prototype.locateById = function(id) {
  node = this.getCurrentNode();
  //load the linked json data
  if (node['type'] && node['link']) {
    //read the file
    var str = readFile(this.jsonPath + '/' + node['link']);
    this.setNode(new JSONDealer(str));
  }
  if (node['data'] && node['type']) {
    this.path.push('data');
    node = node['data'];
  }
  if (node[id] != undefined) {
    this.path.push(id);
    node = node[id];
    return true;
  }
  return false;
};
